import { _decorator, Component, Node, Sprite, Vec3, v3, Label, tween, math, UITransform, Vec2 } from 'cc';
import { Battle } from '../Battle';
import { EnDynamicLineType } from '../Common/const/EnCommon';
import { EnEvent } from '../Common/const/EnEvent';
import { GameAPI } from '../Common/GameAPI';
import { Utitls } from '../Common/Utils';
import { TowerController } from './Tower/TowerController';
const { ccclass, property } = _decorator;

@ccclass('DynamicLine')
export class DynamicLine extends Component {

    @property({ type: Node })
    lineNode: Node = null; // 线段节点
    @property({ type: Node })
    tree: Node = null;
    @property({ type: Node })
    heroTower: Node = null;
    @property({ type: Node })
    tower1Node: Node = null;
    @property({ type: Node })
    tower2Node: Node = null;
    @property({ type: Node })
    tower3Node: Node = null;
    @property({ type: Node })
    tower4Node: Node = null;
    @property({ type: Node })
    mainTowerNode: Node = null;

    pointA: Node = null;                //固定点
    private _lineSprite: Sprite = null; // 线段精灵组件
    private _movementRadius: number = 200; // B点移动半径
    private _movementAngle: number = 0; // B点移动角度
    private _movementSpeed: number = 0.5; // B点移动速度

    private nodeList: Array<Node> = [];

    private isDistance: boolean;

    private curDynamicType: EnDynamicLineType;

    onLoad() {
        // 获取线段精灵组件
        this._lineSprite = this.lineNode.getComponent(Sprite);
    }

    start() {
        this.nodeList.push(this.heroTower);
        this.nodeList.push(this.tower1Node);
        this.nodeList.push(this.tower2Node);
        this.nodeList.push(this.tower3Node);
        this.nodeList.push(this.tower4Node);
        this.nodeList.push(this.mainTowerNode);
        this.pointA = this.mainTowerNode;
        this.curDynamicType = EnDynamicLineType.Default;
        GameAPI.RegGEvent(EnEvent.DynamicLineEvent, this.OnDynamicLineEvent.bind(this), this);
    }

    onDestroy() {
        GameAPI.OffAllCaller(this);
    }

    OnDynamicLineEvent(arg) {
        let targetPoint = null;
        if (this.curDynamicType <= arg.type) {
            //更换目标
            if (arg.type == EnDynamicLineType.Default) {
                targetPoint = this.mainTowerNode;
            }
            else if (arg.type == EnDynamicLineType.InitTree) {
                targetPoint = this.tree;
            }
            else if (arg.type == EnDynamicLineType.UpgradeTower) {
                let minDistance = 1000;
                let playerWorldPos = Battle.playerNode.parent.getWorldPosition();
                for (let index = 1; index < 5; index++) {
                    const element = this.nodeList[index];
                    if (element && element.getComponent(TowerController).noneTower.active) {
                        let point = element.getChildByName("Point");
                        if (point == null) {
                            point = element;
                        }
                        let distance = Vec2.distance(point.getWorldPosition(), playerWorldPos);
                        if (distance < minDistance) {
                            minDistance = distance;
                            targetPoint = element;
                        }
                    }
                }
            }
            else if (arg.type == EnDynamicLineType.CallHero) {
                targetPoint = this.heroTower;
            }
            else if (arg.type == EnDynamicLineType.MainTowerAttacked) {
                targetPoint = this.mainTowerNode;
            }
            this.curDynamicType = arg.type;
        }
        else {
            if (arg.type == EnDynamicLineType.Default) {
                //默认的
                targetPoint = this.mainTowerNode;
            }
        }
        this.SetPointA(targetPoint);
    }

    FilterTargetPoints() {
        let playerWorldPos = Battle.playerNode.parent.getWorldPosition();
        let minDistance = 10000;
        let target = null;
        for (let index = 0; index < this.nodeList.length; index++) {
            const element = this.nodeList[index];
            if (element.active) {
                let point = element.getChildByName("Point");
                if (point == null) {
                    point = element;
                }
                let distance = Vec2.distance(point.getWorldPosition(), playerWorldPos);
                if (distance < minDistance) {
                    minDistance = distance;
                    target = element;
                }
            }
        }
        this.SetPointA(target);
    }

    SetPointA(target) {
        if (target == null) {
            target = this.mainTowerNode;
        }
        let point = target.getChildByName("Point");
        if (point == null) {
            point = target;
        }
        this.pointA = point;
        // this.pointA = target;
    }

    update(dt: number) {
        if (!Battle.startGame) {
            return;
        }
        // 更新点B位置
        this._movementAngle += this._movementSpeed * dt;
        // this.updatePointBPosition();

        // 更新连线
        if (Battle.playerNode && this.pointA) {
            // if (this.isDistance) {
            //     this.FilterTargetPoints();
            // }
            this.updateConnection();
        }
    }

    // 更新点B位置（圆周运动）
    updatePointBPosition() {
        const angleRad = math.toRadian(this._movementAngle);
        const x = this._movementRadius * Math.cos(angleRad);
        const y = this._movementRadius * Math.sin(angleRad);

        this.pointA.setPosition(v3(x, y, 0));
    }

    // 更新连线
    updateConnection() {
        const posA = Battle.playerNode.parent.position;
        let posB = this.pointA.position;
        if (this.pointA.name == "Point") {
            let targetPosition = this.pointA.parent.position;
            const result = new Vec3();
            Vec3.add(result, targetPosition, this.pointA.position);
            posB = result;
        }

        // 计算中点位置
        const midPoint = new Vec3(
            (posA.x + posB.x) / 2,
            (posA.y + posB.y) / 2,
            0
        );
        this.lineNode.setPosition(midPoint);

        // 计算方向向量
        const direction = new Vec3(posB.x - posA.x, posB.y - posA.y, 0);
        const length = direction.length();

        // 计算旋转角度（弧度转角度）
        const angleRad = Math.atan2(direction.y, direction.x);
        const angleDeg = math.toDegree(angleRad);

        // 更新线段
        this.lineNode.setRotationFromEuler(0, 0, angleDeg);
        this._lineSprite.getComponent(UITransform).width = length;
    }

    // 改变运动模式（按钮回调）
    changeMovementMode() {
        this._movementSpeed *= -1;
    }
}